package cn.yunhe.service;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.yunhe.entity.LoginUser;
import cn.yunhe.factory.HibernateSessionFactory;

public class LoginUserService {
	Session session=null;
	Transaction tr=null;
	
	//登录验证
	public LoginUser login(String loginusername,String loginuserpassword) {
		String hql="from LoginUser as l where l.loginusername=? and l.loginuserpassword=?";
		session=HibernateSessionFactory.getSession();
		Query query=session.createQuery(hql);
		query.setString(0, loginusername);
		query.setString(1, loginuserpassword);
		List<LoginUser> list=query.list();
		//判断集合中有没有值，有则返回第一个，没有则返回null;
		return list.size() > 0 ?  list.get(0) : null;
	}
	//注册
	public Boolean reg(String loginusername,String loginuserpassword) {
		String hql="from LoginUser as l where l.loginusername=?";
		session=HibernateSessionFactory.getSession();
		Query query=session.createQuery(hql);
		query.setString(0, loginusername);
		List<LoginUser> list=query.list();
		//判断集合中有没有值，有则返回第一个，没有则返回null;
		if (list.size()<=0) {
			LoginUser loginUser=new LoginUser(loginusername,loginuserpassword);
			session.save(loginUser);
			tr=session.beginTransaction();
			tr.commit();
			return true;
			
		}else {
			tr.rollback();
			return false;
		}
	}
	
}
